package com.zstu.mall.web.admin;

import com.zstu.mall.entity.Product;
import com.zstu.mall.entity.ProductActivity;
import com.zstu.mall.entity.ProductClass;
import com.zstu.mall.entity.pojo.ResultBean;
import com.zstu.mall.service.ProductActivityService;
import com.zstu.mall.service.ProductClassService;
import com.zstu.mall.service.ProductService;
import com.zstu.mall.service.UploadImageService;
import com.zstu.mall.utils.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/product")
public class AdminProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductClassService productClassService;

    @Autowired
    private UploadImageService uploadImageService;

    @Autowired
    private ProductActivityService productActivityService;

    @RequestMapping("/toList.html")
    public String toList(HttpServletRequest request, HttpServletResponse response) {
        //控制最大类型数
        Pageable pageable = new PageRequest(0, 20);
        List<ProductClass> productClasses = productClassService.findByStatus(pageable);
        pageable = new PageRequest(0, 3);
        for(ProductClass productClass : productClasses){
            productClass.setProducts(productService.findByType(productClass.getType(), pageable));
        }
        request.getSession().setAttribute("typelist",productClasses);
        List<ProductActivity> productActivities = productActivityService.findAll();
        request.getSession().setAttribute("activitylist",productActivities);
        System.out.println("session over");
        return "mall/admin/product/productManage";
    }

    @RequestMapping("/toAdd.html")
    public String toAdd() {
        return "admin/product/add";
    }

    @RequestMapping("/toEdit.html")
    public String toEdit(String id, Map<String, Object> map) {
        Product product = productService.get(id);
        ProductClass productClass = productClassService.get(product.getType());
        product.setProductClass(productClass);
        map.put("product", product);
        return "mall/admin/product/productUpdata";
    }

    @ResponseBody
    @RequestMapping("/list.do")
    public ResultBean<List<Product>> listProduct() {
        List<Product> list = productService.findAll();
        return new ResultBean<>(list);
    }

    /**
     * 按分类查找商品
     *
     * @param type
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/category.do")
    public ResultBean<List<Product>> getCategoryProduct(String type, int pageNo, int pageSize) {
        Pageable pageable = new PageRequest(pageNo, pageSize);
        List<Product> products = productService.findByType(type, pageable);
        products = productService.findSoldOn(products);
        return new ResultBean<>(products);
    }

    @ResponseBody
    @RequestMapping("/getTotal")
    public ResultBean<Integer> getTotal() {
        Pageable pageable = PageRequest.of(1, 15);
        int total = (int) productService.findByPage(pageable).getTotalElements();
        return new ResultBean<>(total);
    }

    @RequestMapping("/del.do")
    @ResponseBody
    public ResultBean<Boolean> del(String id) {
        productService.delete(id);
        return new ResultBean<>(true);
    }

    //上架
    @RequestMapping("/soldOn.do")
    @ResponseBody
    public ResultBean<Boolean> soldOn(String id) {
        Product product = productService.get(id);
        boolean result = true;
        if(product.getString1().equals("0"))
            product.setString1("1");
        else
            result = false;
        productService.update(product);
        return new ResultBean<>(result);
    }

    //下架
    @RequestMapping("/soldOut.do")
    @ResponseBody
    public ResultBean<Boolean> soldOut(String id) {
        Product product = productService.get(id);
        boolean result = true;
        if(product.getString1().equals("1"))
            product.setString1("0");
        else
            result = false;
        productService.update(product);
        return new ResultBean<>(result);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/add.do")
    public void add(MultipartFile image1,
                    MultipartFile image2,
                    MultipartFile image3,
                    String title,
                    String name,
                    String type,
                    String activityId,
                    Double price,
                    Double store,
                    Double sales,
                    String content,
                    HttpServletRequest request,
                    HttpServletResponse response) throws Exception {
        Product product = new Product();
        product.setTitle(title);
        product.setName(name);
        product.setType(type);
        product.setActivityId(activityId);
        product.setPrice(price);
        product.setStore(store);
        product.setSales(sales);
        product.setGmtCreate(new Date());
        product.setContent(content);
        String imgUrls = "";
        String imgUrl = FileUtil.saveFile(image1);//第一张主图
        if(imgUrl.contains(".")){//存在图片
            product.setMainImage(imgUrl);
            imgUrls += uploadImageService.findByNewname(imgUrl).getId() + ",";
        }
        else{
            product.setMainImage(uploadImageService.get(imgUrl).getNewName());
            imgUrls += imgUrl + ",";
        }
        if(image2 != null){//后续副图
            imgUrl = FileUtil.saveFile(image2);
            if(imgUrl.contains("."))
                imgUrls += uploadImageService.findByNewname(imgUrl).getId() + ",";
            else
                imgUrls += imgUrl + ",";
        }
        if(image3 != null){//后续副图
            imgUrl = FileUtil.saveFile(image3);
            if(imgUrl.contains("."))
                imgUrls += uploadImageService.findByNewname(imgUrl).getId() + ",";
            else
                imgUrls += imgUrl + ",";
        }
        imgUrls = imgUrls.substring(0, imgUrls.length()-1);
        product.setImage(imgUrls);
        String id = productService.createId();
        product.setId(id);
        if (productService.create(product).getState() == 1) {
            request.setAttribute("message", "添加失败！");
            request.getRequestDispatcher("toAdd.html").forward(request, response);
        } else {
            request.getRequestDispatcher("toEdit.html?id=" + id).forward(request, response);
        }
    }


    @RequestMapping(method = RequestMethod.POST, value = "/update.do")
    public void update(String id,
                       MultipartFile image1,
                       MultipartFile image2,
                       MultipartFile image3,
                       String title,
                       String name,
                       String type,
                       String activityId,
                       Double price,
                       Double store,
                       Double sales,
                       String content,
                       HttpServletRequest request,
                       HttpServletResponse response) throws Exception {
        Product product = productService.get(id);
        product.setTitle(title);
        product.setName(name);
        product.setType(type);
        product.setActivityId(activityId);
        product.setPrice(price);
        product.setStore(store);
        product.setSales(sales);
        product.setContent(content);
        product.setGmtModified(new Date());
        String imgUrls = "";
        String imgUrl = FileUtil.saveFile(image1);//第一张主图
        if(imgUrl.contains(".")){//存在图片
            product.setMainImage(imgUrl);
            imgUrls += uploadImageService.findByNewname(imgUrl).getId() + ",";
        }
        else{
            product.setMainImage(uploadImageService.get(imgUrl).getNewName());
            imgUrls += imgUrl + ",";
        }
        if(image2 != null){//后续副图
            imgUrl = FileUtil.saveFile(image2);
            if(imgUrl.contains("."))
                imgUrls += uploadImageService.findByNewname(imgUrl).getId() + ",";
            else
                imgUrls += imgUrl + ",";
        }
        if(image3 != null){//后续副图
            imgUrl = FileUtil.saveFile(image3);
            if(imgUrl.contains("."))
                imgUrls += uploadImageService.findByNewname(imgUrl).getId() + ",";
            else
                imgUrls += imgUrl + ",";
        }
        imgUrls = imgUrls.substring(0, imgUrl.length()-1);
        product.setImage(imgUrls);
        boolean flag = false;
        try {
            productService.update(product);
            flag = true;
        } catch (Exception e) {
            throw new Exception(e);
        }
        if (!flag) {
            request.setAttribute("message", "更新失败！");
        }
        response.sendRedirect("toList.html");
    }

    //图片
    @RequestMapping(method = RequestMethod.GET, value = "/img/{filename:.+}")
    public void getImage(@PathVariable(name = "filename", required = true) String filename,
                         HttpServletResponse res) throws IOException {
        File file = new File("file/" + filename);
        if (file != null && file.exists()) {
            res.setHeader("content-type", "application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            res.setContentLengthLong(file.length());
            Files.copy(Paths.get(file.toURI()), res.getOutputStream());
        }
    }
}